#include "tagdialog.h"
#include "ui_tagdialog.h"
#include "controller.h"
#include "utility.h"
#include "feats/thememanager.h"

#include "../deps/taglib/include/tag.h"
#include "../deps/taglib/include/fileref.h"

#include <QPaintEvent>
#include <QPainter>

TagDialog::TagDialog(QWidget *parent) :
    QThemeableDialog(parent),
    ui(new Ui::TagDialog),
    _fref(NULL), _tag(NULL)
{
    ui->setupUi(this);

    ui->titleBar->showMinimize(false);

    connect(this, SIGNAL(accepted()), SLOT(saveTags()));
    connect(ui->titleBar, SIGNAL(close()), SLOT(reject()));
}

TagDialog::~TagDialog()
{
    delete ui;
    delete _fref;
}

void TagDialog::setReadOnly(bool value)
{
    util::set_whole_widget_readonly(this, value);
}

void TagDialog::setFile(QString path)
{
    TagLib::FileName fname(path.utf16());
    _fref = new TagLib::FileRef(fname);
    if ( _fref->isNull() )
    {
        delete _fref; _fref = NULL;
        return;
    }

    _tag = _fref->file()->tag();
    loadTags();
}

bool TagDialog::loadTags()
{
    if (!_tag)
        return false;
    QString comment, album, artist, title, genre;
    QString year, track;
    util::tagstring_to_qstring(&_tag->comment(), "", &comment);
    util::tagstring_to_qstring(&_tag->album(), "", &album);
    util::tagstring_to_qstring(&_tag->artist(), "", &artist);
    util::tagstring_to_qstring(&_tag->title(), "", &title);
    util::tagstring_to_qstring(&_tag->genre(), "", &genre);

    year.setNum(_tag->year());
    track.setNum(_tag->track());

    ui->teComment->setPlainText(comment);
    ui->txAlbum->setText(album);
    ui->txArtist->setText(artist);
    ui->txTitle->setText(title);
    ui->txGenre->setText(genre);
    ui->txYear->setText(year);
    ui->txTrack->setText(track);

    return true;
}

bool TagDialog::saveTags()
{
    if (!_fref || !_fref->file() || !_tag)
        return false;
    TagLib::String album, artist, title, comment, genre;

    album = ui->txAlbum->text().utf16();
    artist = ui->txArtist->text().utf16();
    title = ui->txTitle->text().utf16();
    genre = ui->txGenre->text().utf16();
    comment = ui->teComment->toPlainText().utf16();

    bool yearok, trackok;
    int year = ui->txYear->text().toInt(&yearok, 10);
    int track = ui->txTrack->text().toInt(&trackok, 10);

    _tag->setAlbum(album);
    _tag->setArtist(artist);
    _tag->setTitle(title);
    _tag->setComment(comment);
    _tag->setGenre(genre);
    if (yearok)
        _tag->setYear(year);
    if (trackok)
        _tag->setTrack(track);
    bool ret = _fref->file()->save();
    return ret;
}

void TagDialog::changeEvent(QEvent *e)
{
    QDialog::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}
